/*******************************************************************************
 * Copyright (c) 2002 Boris Pruessmann and others. All rights reserved. This
 * program and the accompanying materials are made available under the terms of
 * the Common Public License v0.5 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors: Boris Pruessmann - Initial implementation.
 ******************************************************************************/
package net.sourceforge.perforce.core.internal.api;

import com.google.common.collect.Sets;

import net.sourceforge.perforce.core.PerforceException;
import net.sourceforge.perforce.core.api.IPerforceServer;
import net.sourceforge.perforce.core.api.IWhereResult;

import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.runtime.Path;

import java.util.Set;

/**
 * @version $Revision: 488 $
 * @author <a href="mailto:bpruessmann@users.sourceforge.net">Boris
 *         Pruessmann</a>
 */
public class ChangeSpec {
  // ---------------------------------------------------------------------------
  // Private Variables

  /** Stores the Perforce spec string. */
  private String specString;
  /** Stores the affected files. */
  private String[] files;

  // -------------------------------------------------------------------------
  // Public Constructors

  /**
   * Constructor for ChangeSpec.
   * 
   * @param theSpecString the Perforce spec string.
   * @param theFiles the affected files.
   */
  public ChangeSpec(String theSpecString, String[] theFiles) {
    specString = theSpecString;
    files = theFiles;
  }

  //----------------------------------------------------------------------------
  // -- Public Methods

  /**
   * Returns the number of affected files.
   * 
   * @return the file count.
   */
  public int getFileCount() {
    return files.length;
  }

  /**
   * Returns an array of affected files (depot syntax)
   * 
   * @return affected files
   */
  public String[] getFiles() {
    return files;
  }

  @Override
  public String toString() {
    return specString;
  }

  public Set<IResource> getResources(IPerforceServer server, IWorkspaceRoot root)
      throws PerforceException {
    Set<IResource> resources = Sets.newHashSet();
    for (String file : files) {
      IWhereResult whereResult = server.where(file);

      Path location = new Path(whereResult.getLocalFilename());
      IResource resource = root.getFileForLocation(location);
      if (resource != null && resource.exists()) {
        resources.add(resource);
      }
    }
    return resources;
  }
}
